<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button style="margin-left: 10px" class="filter-item" type="primary" icon="el-icon-plus"
                 @click="openCreateWindow">
        新增
      </el-button>
    </div>
    <el-divider/>
    <el-table
      key="ota-upgrade"
      ref="ota"
      :loading="listLoading"
      :cell-style="{padding:0+'px'}"
      :data="list"
      :row-style="{height:40+'px'}"
      border
      fit
      height="700"
      highlight-current-row
      stripe
      style="width: 100%;"
    >
      <el-table-column
        type="index"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column align="center" label="名称">
        <template v-slot="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="优惠模式">
        <template v-slot="{row}">
          <span>{{ row.method | paymentModelText }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="起送金额">
        <template v-slot="{row}">
          <span>{{ row.start_amount }}元</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="赠送额度">
        <template v-slot="{row}">
          <span>{{ row | rebateText }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="80">
        <template v-slot="{row}">
          <el-switch
            v-model="row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)">
          </el-switch>

        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template v-slot="{row}">
          <span>{{ formatDate(row.create_date) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="80px"
        label="操作" >
        <template v-slot="{row}">
          <el-button  circle icon="el-icon-edit" type="primary"
                      @click="openUpdateWindow(row)" size="mini" />
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                @pagination="fetchData"/>
    <el-dialog :title="dialogTitleMap[dialogStatus]" :visible.sync="dialogCreateVisible"
               width="30%"
               custom-class="window-small-width"
               :close-on-click-modal="false">
      <el-form ref="createForm" :rules="createForm.rules" :model="createForm.model" :loading="formLoading"
               element-loading-text="优惠规则创建中..."
               element-loading-spinner="el-icon-loading" label-position="right" label-width="100px">
        <el-form-item label="名称:" prop="name">
          <el-input v-model="createForm.model.name" class="filter-item"  clearable
                    placeholder="名称"/>
        </el-form-item>
        <el-form-item label="优惠模式:" prop="method">
          <el-select v-model="createForm.model.method" placeholder="请选择">
            <el-option
              v-for="item in methods"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起送金额:" prop="start_amount">
          <el-input v-model.number="createForm.model.start_amount" class="filter-item"  clearable
                    placeholder="0.00">
            <el-button slot="append" >元</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="赠送额度:" prop="rebate_amount">
          <el-input v-model.number="createForm.model.rebate_amount" class="filter-item"  clearable
                    placeholder="0.00"  >
            <el-button slot="append" >{{createForm.model.method === 1 ? '元' : '%'}}</el-button>
          </el-input>

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">
          取消
        </el-button>
        <el-button :loading="btnLoading" type="primary" @click="dialogStatus === 'create' ? submitPrice(createForm.model) : updatePrice(createForm.model)">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {createDiscount, updateDiscount, disableDiscount,enableDiscount,fetchList} from "@/api/discount";
import Pagination from '@/components/Pagination'
import {getToken} from "@/utils/auth";
import jsUtils from 'jutils-src'

const methods = [
  {'name':'赠送指定金额','value':1},
  {'name':'赠送充值百分比','value':2}
]

export default {
  name: "Discount",
  components: {Pagination},
  data() {
    return {
      dialogStatus:'create',
      listLoading: false,
      formLoading: false,
      btnLoading: false,
      methods: methods,
      dialogCreateVisible: false,
      dialogPriceRateVisible: false,
      dialogTitleMap: {
        update: '编辑优惠规则',
        create: '新增优惠规则'
      },
      listQuery: {
        status:-1,
        pageSize: 20,
        page: 1
      },
      importData: {},
      list: [],
      files: [],
      total: 0,
      token: '',
      createForm: {
        rules: {
          name: [
            {required: true, message: '请输入优惠规则名称', trigger: 'blur'}
          ],
          start_amount: [
            {required: true, message: '请输入起送金额', trigger: 'blur'}
          ],
          rebate_amount: [
            {required: true, message: '请输入赠送额度', trigger: 'blur'}
          ]
        },
        model: {
          name: null,
          method:1,
          start_amount: 0.00,
          rebate_amount: 0.00
        }
      }
    }
  },
  filters: {
    statusText(val) {
      const t = ['已启用', '未启用']
      return t[val]
    },
    statusColor(val) {
      const t = ['default', 'upgrading', 'success', 'failed', 'cancel']
      return t[val]
    },
    unitText(val) {
      const t = ['m³','升']
      return t[val-1]
    },
    paymentModelText(val) {
      const t = ['赠送指定金额', '赠送充值百分比']
      return t[val-1]
    },
    rebateText(val) {
     if(val.method === 1) {
       return val.rebate_amount +'元'
     }else{
       return val.rebate_amount +'%'
     }
    }
  },
  created() {
    this.fetchData()
    this.token = getToken()
  },
  methods: {
    fetchData() {
      fetchList(this.listQuery).then(res => {
        if (res.code === 20000) {
          this.list = res.data.list
          this.total = res.data.total
        }
      }).catch(err => {
        this.$message.error(err)
      })
    },
    openCreateWindow() {
      this.dialogCreateVisible = true
      this.dialogStatus = 'create';
      this.createForm.model = Object.assign({},{
        name: null,
        method:1,
        start_amount: 0.00,
        rebate_amount: 0.00
      })
    },
    submitPrice() {
      this.$refs['createForm'].validate((valid) => {
        if(valid) {
          createDiscount(this.createForm.model).then(resp => {
            if(resp.code === 20000) {
              this.$message.success('创建成功')
              this.dialogCreateVisible = false
              this.fetchData()
            }
          })
        }
      });
    },
    openUpdateWindow(row) {
      this.dialogCreateVisible = true
      this.dialogStatus = 'update'
      this.createForm.model = Object.assign({},row)
    },
    updatePrice() {
      this.$refs['createForm'].validate((valid) => {
        if(valid) {
          updateDiscount(this.createForm.model).then(resp => {
            if(resp.code === 20000) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogCreateVisible = false
              this.fetchData()
            }
          })
        }
      });
    },
    handleStatusChange(row) {
      if(row.status === 0) {
        this.handleDisablePrice(row)
      }else {
        this.handleEnablePrice(row)
      }
    },
    handleDisablePrice(row){
      this.$confirm('确定要禁用优惠方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        disableDiscount(row).then(resp => {
          if(resp.code === 20000) {
            this.$message.success('禁用成功')
            row.status = 0
          }
        })
      }).catch((e) => {
        if (e === 'cancel') {
          row.status = 1
        }else {
          this.$message.error(e)
        }
      })
    },
    handleEnablePrice(row){
      this.$confirm('确定要启用该优惠方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enableDiscount(row).then(resp => {
          if(resp.code === 20000) {
            this.$message.success('启用成功')
            row.status = 1
          }
        })
      }).catch(err => {
        if (err === 'cancel') {
          row.status = 0
        }else {
          this.$message.error(err)
        }
      })
    },
    formatDate(dateStr) {
      return jsUtils.formatDate(new Date(dateStr), 'YYYY-MM-DD')
    },
  }
}
</script>

<style scoped>
.upgrading {
  color: blue;
}

.failed {
  color: red;
}

.success {
  color: green;
}

.cancel {
  color: grey;
}
</style>
